import React, { useEffect, useState } from 'react'
import DetailContainer from '@/components/DetailContainer'
import Descriptions from '@/components/Descriptions'
import { Button, Form, message, Space, Typography } from 'antd'
import { EditFormInline } from '@/components/CustomForm'
import { useFormBase } from '../useForm'
import { FormInstance, useForm } from 'antd/es/form/Form'
import { useNavigate, useSearchParams } from 'react-router-dom'
import './FormShare.less'
import UploadFile from '@/components/UploadFile'
import useGetProDevSeason, { IProDevSeason } from '@/hooks/useGetProDevSeason'
import { ITableData } from '../types'
import dayjs from 'dayjs'
import { useAppSelector } from '@/store/hooks'
import { createProductPlanning, getProductPlanningById, updateProductPlanning } from '@/api/goods'
import { downloadByUrl, getNameByOwnUrl } from '@/utils/util'
import useViewLogs from '@/hooks/useViewLogs'
import { OperationLogType } from '@/constant'
import LogsDrawer from '@/components/LogsDrawer'
import PermissionButton from '@/components/PermissionButton'
import useGetClassIds from '@/hooks/useGetClassIds'
const Index: React.FC = () => {
  const [FormPlan] = useForm()
  const [ispedding, setispedding] = useState<boolean>(false)
  const [detailInfo, setDetail] = useState<Record<string, any>>({})
  const [desInfoList, setDesInfoList] = useState<IDesListType>([
    { label: '开发季', key: 'devSeasonName', content: '-' },
    { label: '年份', key: 'yearValue', content: '-' },
    { label: '商品企划编号', key: 'planNo', content: '-' },
  ])
  //企划信息
  const [isbaseinfoEdit, setisbaseinfoEdit] = useState<boolean>(false)
  const [baseinfoList, setbaseinfoList] = useState<IDesListType>([
    // { label: '开发季', key: 'devSeasonName', content: '-' },
    // { label: '年份', key: 'yearValue', content: '-' },
    {
      label: '款式分类',
      key: 'bigClassName',
      content: '-',
      format(detailInfo) {
        return (
          (detailInfo.bigClassName ? detailInfo.bigClassName : '') +
          (detailInfo.midClassName ? '-' + detailInfo.midClassName : '') +
          (detailInfo.smallClassName ? '-' + detailInfo.smallClassName : '') +
          (detailInfo.tinyClassName ? '-' + detailInfo.tinyClassName : '')
        )
      },
    },
    { label: '适销季节', key: 'seasonCodeName', content: '-' },
    { label: '上市日期', key: 'releaseSeasonDateStr', content: '-' },
    { label: '过季日期', key: 'overSeasonDateStr', content: '-' },
    { label: '企划毛利率', key: 'planRateStr', content: '-' },
    { label: '毛利率下限', key: 'profitRateLowerLimitStr', content: '-' },
    { label: '吊牌价', key: 'originSalePrice', content: '-' },
    { label: '价格带', key: 'priceTagCode', content: '-' },
    { label: '价格属性', key: 'priceProperty', content: '-' },
    { label: '定价权限', key: 'priceAuth', content: '-' },
    { label: '企划SKC数量', key: 'skcPlanNum', content: '-' },
    { label: '开发定位', key: 'devLocation', content: '-' },
    { label: '季节分组', key: 'seasonGroup', content: '-' },
    { label: '商品等级', key: 'productLevel', content: '-' },
    { label: '适销年龄段', key: 'suitAgeGroup', content: '-' },
    // { label: '设计师/买手', key: 'designerName', content: '-' },
    { label: '商品描述', key: 'productDesc', content: '-' },
  ])
  const [isuploadEdit, setisuploadEdit] = useState<boolean>(false)
  const [query] = useSearchParams()
  const navigate = useNavigate()
  const { classIdOptions } = useGetClassIds()
  const ProDevSeason = useGetProDevSeason()
  const DICTDATA = useAppSelector((state) => state.login.DICTDATA)
  const planingId = query.get('planingId')
  const updateSalesPrice = Form.useWatch('updateSalesPrice', FormPlan)
  const { isLogShow, setisLogShow, logLoading, logInfos, setLogInfos, viewLogs } = useViewLogs(
    'planingId',
    OperationLogType.PRODUCTPLAN,
  )
  useEffect(() => {
    if (planingId) {
      getDetail()
    } else {
      setisbaseinfoEdit(true)
      setisuploadEdit(true)
    }
  }, [])
  const onValuesChange = (changedValues: any, trimKeys: string[], form: FormInstance) => {
    trimKeys.forEach((key) => {
      if (changedValues[key]) {
        const trimmedKey = changedValues[key].trim()
        form.setFieldsValue({
          [key]: trimmedKey,
        })
      }
    })
  }
  const getDetail = async () => {
    const res = await getProductPlanningById<ITableData>({ planingId })
    if (res.code === 200) {
      const details = res.data
      setDetail(details)
      details?.planNo && (document.title = details.planNo)
      handleDetailFactory(baseinfoList, details, setbaseinfoList)
      handleDetailFactory(desInfoList, details, setDesInfoList)
      FormPlan.setFieldsValue({
        releaseSeasonDate: details.releaseSeasonDate && dayjs(details.releaseSeasonDate),
        overSeasonDate: details?.overSeasonDate && dayjs(details.overSeasonDate),
        planRate: details?.planRate,
        profitRateLowerLimit: details?.profitRateLowerLimit,
        originSalePrice: details?.originSalePrice,
        priceTagCode: details?.priceTagCode,
        priceProperty: details?.priceProperty,
        priceAuth: details?.priceAuth,
        skcPlanNum: details?.skcPlanNum,
        devLocation: details?.devLocation,
        seasonGroup: details?.seasonGroup,
        suitAgeGroup: details?.suitAgeGroup,
        productLevel: details?.productLevel,
        designerName: details?.designerName,
        fileId: details?.fileId,
        productDesc: details?.productDesc,
        seasonCode: details?.seasonCode,
        classPath: details?.classPath,
      })
    }
  }
  const startEdit = async (setisEdit: React.Dispatch<React.SetStateAction<boolean>>) => {
    FormPlan.validateFields().then(async (data) => {
      setisEdit(true)
      delete data.year
      const params = {
        ...data,
        overSeasonDate: data.overSeasonDate
          ? dayjs(data.overSeasonDate).format('YYYY-MM-DD HH:mm:ss')
          : detailInfo?.overSeasonDateStr + ' 00:00:00',
        releaseSeasonDate: data.releaseSeasonDate
          ? dayjs(data.releaseSeasonDate).format('YYYY-MM-DD HH:mm:ss')
          : detailInfo?.releaseSeasonDateStr + ' 00:00:00',
        fileId: data.fileId,
        classId: data.classPath && data.classPath.length > 0 ? data.classPath[data.classPath.length - 1] : null,
      }
      if (data.classPath && data.classPath.length > 0 && data.classPath.length !== 4) {
        message.warning('款式分类没有选择到细类')
        return
      }
      let res: IResponsePost<unknown>
      if (!planingId) {
        setispedding(true)
        res = await createProductPlanning(params).finally(() => setispedding(false))
      } else {
        const editParams = {
          ...detailInfo,
          ...params,
          seasonId: detailInfo.seasonId,
          classId:
            data.classPath && data.classPath.length > 0
              ? data.classPath[data.classPath.length - 1]
              : detailInfo?.classPath[detailInfo?.classPath.length - 1],
          planingId: planingId,
        }
        setispedding(true)
        res = await updateProductPlanning(editParams).finally(() => setispedding(false))
      }
      if (res.code === 200) {
        setisEdit(false)
        message.open({
          type: 'success',
          content: (
            <Typography.Text>
              {planingId ? '' : '新建'}商品企划{planingId ? '修改' : ''}成功，企划编号：
              <Typography.Link onClick={() => navigate('/goods/plan/detail?planingId=' + res?.data?.planId)}>
                {res?.data?.planNo}
              </Typography.Link>
            </Typography.Text>
          ),
          duration: 5,
        })
        if (!planingId) {
          navigate('/goods/plan/list')
        } else {
          getDetail()
        }
      }
    })
  }
  const handleYearChange = (_: number, info: IProDevSeason) => {
    FormPlan.setFieldValue('year', dayjs(info.year + ''))
  }
  const onValuesFormChange = (changedValues: any) => {
    onValuesChange(changedValues, ['updateReason', 'designerName', 'productDesc'], FormPlan)
  }
  const onDownload = (info: string) => {
    downloadByUrl(info)
  }
  const handleDetailFactory = (
    sourceList: IDesListType,
    targetInfo: any,
    set: React.Dispatch<React.SetStateAction<IDesListType>>,
  ) => {
    const res = sourceList?.map((item) => {
      if (typeof item.format === 'function') {
        return {
          ...item,
          content: item.format(targetInfo),
        }
      } else {
        return {
          ...item,
          content: targetInfo[item.key + ''] || '-',
        }
      }
    })
    set(res)
  }
  return (
    <DetailContainer
      className="goods_plan_add_page"
      footer={
        <Space>
          {planingId && Object.keys(detailInfo).length > 0 && (
            <Button type="primary" ghost onClick={() => viewLogs(detailInfo)}>
              查看日志
            </Button>
          )}
          {!planingId && (
            <Button type="primary" onClick={() => startEdit(setisbaseinfoEdit)} loading={ispedding}>
              保存
            </Button>
          )}
        </Space>
      }
    >
      {planingId && <Descriptions title="基础信息" list={desInfoList}></Descriptions>}
      <Descriptions
        title="企划信息"
        list={isbaseinfoEdit ? [] : baseinfoList}
        extra={
          <Space>
            {planingId && (
              <PermissionButton
                permission="editPlan"
                loading={ispedding}
                type="primary"
                onClick={async () => {
                  if (isbaseinfoEdit) {
                    startEdit(setisbaseinfoEdit)
                  } else {
                    setisbaseinfoEdit(true)
                  }
                }}
              >
                {isbaseinfoEdit ? '保存修改' : '编辑'}
              </PermissionButton>
            )}
            {planingId && isbaseinfoEdit ? (
              <Button
                onClick={() => {
                  setisbaseinfoEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        <EditFormInline
          form={FormPlan}
          className="sep_forminline_style"
          editConfig={useFormBase({
            isEdit: isbaseinfoEdit && !!planingId,
            ProDevSeason,
            DICTDATA,
            handleYearChange,
            classIdOptions,
            updateSalesPrice,
          })}
          onValuesChange={onValuesFormChange}
          initialValues={{ releaseSeasonDate: dayjs(), overSeasonDate: dayjs(), year: null }}
        />
      </Descriptions>
      <Descriptions
        title="附件信息"
        extra={
          <Space>
            {planingId && (
              <PermissionButton
                permission="editPlan"
                loading={ispedding}
                type="primary"
                onClick={async () => {
                  if (isuploadEdit) {
                    startEdit(setisuploadEdit)
                  } else {
                    setisuploadEdit(true)
                  }
                }}
              >
                {isuploadEdit ? '保存修改' : '编辑'}
              </PermissionButton>
            )}
            {planingId && isuploadEdit ? (
              <Button
                onClick={() => {
                  setisuploadEdit(false)
                }}
              >
                取消
              </Button>
            ) : null}
          </Space>
        }
      >
        {isuploadEdit ? (
          <Form className="upload_file_wrap" form={FormPlan} layout="vertical" onValuesChange={onValuesFormChange}>
            <Form.Item label="附件上传" name="fileId">
              <UploadFile></UploadFile>
            </Form.Item>
          </Form>
        ) : detailInfo?.fileId ? (
          <Space size={'large'}>
            {detailInfo?.fileId?.split(',')?.map((item: string) => {
              return (
                <Typography.Link key={item} onClick={() => onDownload(item)}>
                  {getNameByOwnUrl(item)}
                </Typography.Link>
              )
            })}
          </Space>
        ) : (
          '-'
        )}
      </Descriptions>
      <LogsDrawer {...{ isLogShow, setisLogShow, logLoading, logInfos, setLogInfos }}></LogsDrawer>
    </DetailContainer>
  )
}
export default Index
